package dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.util.ArrayList;

import connectUtil.ConnectionUtil;
import entity.BookTour;
import entity.Tour;
import entity.Visitor;

public class BookTourDAO {
	private static Connection conn;
    private static CallableStatement callProc;
    private static ResultSet rs;
    
    public static boolean bookTour(int visitorID, int tourID, short numberOfSlot, Date date) {
    	try {
    		conn = ConnectionUtil.getConnection();
    		callProc = conn.prepareCall("{call addBookTour(?, ?, ?, ?)}");
    		callProc.setInt(1, visitorID);
    		callProc.setInt(2, tourID);
    		callProc.setShort(3, numberOfSlot);
    		callProc.setDate(4, date);
    		
    		if (callProc.executeUpdate() == 0) {
    			throw new Exception();
    		}
    		
    		return true;    		
    	} catch (Exception ex) {
    		System.out.println(" Error from booktourdao: " + ex.getMessage());
    	    return false;
    	} finally {
    		ConnectionUtil.closeConnections(conn, callProc, null);
    	}
    }
    
    public static ArrayList<BookTour> getListBookTour() {
    	ArrayList<BookTour> list = new ArrayList<BookTour>();
    	BookTour bookTour;
    	Tour tour;
    	Visitor visitor;
    	int id;
    	short numberOfSlot;
    	Date bookingDay;
    	
    	try {
    		conn = ConnectionUtil.getConnection();
    		callProc = conn.prepareCall("{call getListBookTour()}");
    		rs = callProc.executeQuery();
    		
    		while (rs.next()) {
    			visitor = new Visitor();
    			tour = new Tour();
    			id = rs.getInt("id");
    			visitor.setUserName(rs.getString("userName"));
    			tour.setTourName(rs.getString("tourName"));
    			tour.setPlace(rs.getString("place"));
    			tour.setStartDate(rs.getDate("startDate"));
    			tour.setEndDate(rs.getDate("endDate"));
    			numberOfSlot = rs.getShort("numberOfSlot");
    			bookingDay = rs.getDate("bookingDay");
    			bookTour = new BookTour(id, visitor, tour, numberOfSlot, bookingDay);
    			list.add(bookTour);
    		}
    		   		
    	} catch (Exception ex) {
    		System.out.println(" Error from booktourdao: " + ex.getMessage());
    	} finally {
    		ConnectionUtil.closeConnections(conn, callProc, rs);
    	}
    	
    	return list;
    }
}
